import baseUrl from "@/common/config.js";
// #ifdef APP-PLUS
var COS = require("@/common/js_sdk/cos-jdk/cos-wx-sdk-v5.js")
// #endif
// #ifdef H5
var COS = require("@/common/js_sdk/cos-jdk/h5/cos-js-sdk-v5.min.js");
// #endif
// 上传服务器的方法
  export function putFile (filePath, callback) {
  	//获取后缀
  	var filarr = null
  	var ext = null
  	// #ifdef H5
  	ext = filePath.type.split('/')[1]
  	// #endif
  	// #ifdef APP-PLUS 
  	filarr = filePath.split('.')
  	ext = filarr[filarr.length - 1]
  	// #endif
  	console.log("ext>>>>>>>>>>", ext)
  	// 异步获取临时密钥
  	var data, credentials, bucket, region, filename, url
  	uni.request({
  		url: baseUrl.getTempKey,
  		method: "POST",
  		data: {
  			// 用户id
  			unid: 1,
  			// 文件类型
  			type: 'image',
  			ext: ext
  		},
  		success: (result) => {
  			console.log("result", result)
  			data = result.data;
  			bucket = data.data.bucket
  			region = data.data.region
  			filename = data.data.filepath
  			credentials = data.data.credentials;
  			//实例化
  			var cos = new COS({
  				getAuthorization: function (options, callback) {
  					callback({
  						TmpSecretId: credentials.tmpSecretId,
  						TmpSecretKey: credentials.tmpSecretKey,
  						XCosSecurityToken: credentials.sessionToken,
  						// 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
  						StartTime: data.data.startTime, // 时间戳，单位秒，如：1580000000
  						ExpiredTime: data.data.expiredTime, // 时间戳，单位秒，如：1580000900
  					});
  				}
  			});
  			uni.showLoading({
  				title: '上传中'
  			});
  			// #ifdef APP-PLUS 
  			cos.postObject({
  				Bucket: bucket,
  				Region: region,
  				Key: filename,
  				FilePath: filePath,
  				onProgress: function (info) {
  					console.log(JSON.stringify(info));
  				}
  			}, requestCallback)
  			// #endif
  			// #ifdef H5
  			cos.putObject({
  				Bucket: bucket,
  				Region: region,
  				Key: filename,
  				StorageClass: "STANDARD",
  				Body: filePath,
  				onProgress: function (info) {
  					console.log(JSON.stringify(info));
  				},
  			}, requestCallback)
  			// #endif
  		}
  	});
  	// 回调统一处理函数
  	var requestCallback = (err, data) => {
  		if (err && err.error) {
  			uni.showModal({
  				title: '返回错误',
  				content: '请求失败：' + (err.error.Message || err.error) + '；状态码：' + err.statusCode,
  				showCancel: false
  			});
  			uni.hideLoading()
  		} else if (err) {
  			uni.showModal({
  				title: '请求出错',
  				content: '请求出错：' + err + '；状态码：' + err.statusCode,
  				showCancel: false
  			});
  			uni.hideLoading()
  		} else {
  			url = 'http://' + data.Location
  			uni.hideLoading()
  			callback({
  				successUrl: url
  			})
  		}
  	};
  }
